package test.com.qu.myapplication.service;

import android.app.AlarmManager;
import android.app.Notification;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Resources;
import android.net.Uri;
import android.os.IBinder;
import android.os.RemoteException;
import android.support.annotation.Nullable;
import android.support.v4.app.NotificationCompat;
import android.support.v4.app.NotificationManagerCompat;
import android.util.Log;

import com.loopj.android.http.TextHttpResponseHandler;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

import cz.msebera.android.httpclient.Header;
import test.com.qu.myapplication.INotificationService;
import test.com.qu.myapplication.MainActivity;
import test.com.qu.myapplication.Notice;
import test.com.qu.myapplication.R;

/**
 * Created by Administrator on 2017/3/14.
 */

public class NoticeService extends Service{
    public static final String INTENT_ACTION_BROADCAST = "net.oschina.app.service.BROADCAST";
    public static final String INTENT_ACTION_SHUTDOWN = "net.oschina.app.service.SHUTDOWN";
    public static final String INTENT_ACTION_REQUEST = "net.oschina.app.service.REQUEST";
    private static final long INTERVAL = 1000 * 120;
    private AlarmManager mAlarmMgr;

    private List<Notice> mNotice;
    private final BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (INTENT_ACTION_BROADCAST.equals(action)) {
                if (mNotice != null) {
                    //UIHelper.sendBroadCast(NoticeService.this, mNotice);
                }
            } else if (INTENT_ACTION_SHUTDOWN.equals(action)) {
                stopSelf();
            } else if (INTENT_ACTION_REQUEST.equals(action)) {
                //requestNotice();
            }
        }
    };
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return mBinder;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        mAlarmMgr = (AlarmManager) getSystemService(ALARM_SERVICE);
        startRequestAlarm();
        requestNotice();
        IntentFilter filter = new IntentFilter(INTENT_ACTION_BROADCAST);
        filter.addAction(INTENT_ACTION_SHUTDOWN);
        filter.addAction(INTENT_ACTION_REQUEST);
        registerReceiver(receiver, filter);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return super.onStartCommand(intent, flags, startId);
    }
    private void startRequestAlarm() {
        cancelRequestAlarm();
        // 从1秒后开始，每隔2分钟执行getOperationIntent()
        mAlarmMgr.setRepeating(AlarmManager.RTC_WAKEUP,
                System.currentTimeMillis() + 1000, INTERVAL,
                getOperationIntent());
    }
    private void cancelRequestAlarm() {
        mAlarmMgr.cancel(getOperationIntent());
    }
    /**
     * OSC采用轮询方式实现消息推送<br>
     * 每次被调用都去执行一次{@link #}onReceive()方法
     *
     * @return
     */
    private PendingIntent getOperationIntent() {
        Intent intent = new Intent(this, AlarmReceiver.class);
        PendingIntent operation = PendingIntent.getBroadcast(this, 0, intent,
                PendingIntent.FLAG_UPDATE_CURRENT);
        return operation;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        unregisterReceiver(receiver);
        cancelRequestAlarm();
    }
    private final TextHttpResponseHandler requestHandler = new TextHttpResponseHandler() {
        @Override
        public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
            Log.d("NoticeService","statusCode:"+statusCode);
        }

        @Override
        public void onSuccess(int statusCode, Header[] headers, String responseString) {
            Log.d("NoticeService","onSuccess()-----------:"+statusCode);

        }
    };
    /**
     * 请求是否有新通知
     */
    private void requestNotice() {
        Api.Newnotifications(requestHandler);
    }
    private static class ServiceStub extends INotificationService.Stub{
        WeakReference<NoticeService> mService;

        ServiceStub(NoticeService service) {
            mService = new WeakReference<NoticeService>(service);
        }
        @Override
        public void requestNotice() throws RemoteException {
            mService.get().requestNotice();
        }
    }
    private final IBinder mBinder = new ServiceStub(this);
    private int lastNotifiyCount;
    private void notification(List<Notice> notice) {
        int count = notice.size();

        if (count == 0) {
            lastNotifiyCount = 0;
            NotificationManagerCompat.from(this).cancel(
                    R.string.you_have_news_messages);
            return;
        }
        if (count == lastNotifiyCount)
            return;

        lastNotifiyCount = count;

        Resources res = getResources();
        String contentTitle = res.getString(R.string.you_have_news_messages,
                count);
        Intent intent = new Intent(this, MainActivity.class);
        intent.putExtra("NOTICE", true);

        PendingIntent pi = PendingIntent.getActivity(this, 1000, intent,
                PendingIntent.FLAG_CANCEL_CURRENT);

        NotificationCompat.Builder builder = new NotificationCompat.Builder(
                this).setTicker(contentTitle).setContentTitle(contentTitle)
                .setContentText("消息列表中...").setAutoCancel(true)
                .setContentIntent(pi).setSmallIcon(R.mipmap.ic_launcher);

            //声音
            builder.setSound(Uri.parse("android.resource://"
                    + App.getInstance().getPackageName() + "/"
                    + R.raw.notificationsound));

            //震动
            long[] vibrate = { 0, 10, 20, 30 };
            builder.setVibrate(vibrate);


        Notification notification = builder.build();

        NotificationManagerCompat.from(this).notify(
                R.string.you_have_news_messages, notification);
    }
}
